import redis.clients.jedis.Jedis;

import java.util.Scanner;
import java.util.UUID;

/**
 * @author 帅小伙
 * @date 2021/12/31
 * @description
 */
public class PhoneCode {


    public static void main(String[] args) {
        Jedis jedis = new Jedis("47.96.19.90", 23333);
        verifyCode("155");
        Scanner scanner = new Scanner(System.in);
        String verifyCode = scanner.next();
        getRedisCode("155",verifyCode);
    }

    //3.验证码校验
    public static void getRedisCode(String phone, String code){
        Jedis jedis = new Jedis("47.96.19.90", 23333);
        String codeKey =  "VerifyCode" + phone + ":code";
        String redisCode = jedis.get(codeKey);

        if(code.equals(redisCode)){
            System.out.println("验证码正确");
        }else{
            System.out.println("验证码错误或超时");
        }

        jedis.close();
    }

    //2.每个手机每天只能发送3次   验证码放在redis中 设置过期时间
    public static void verifyCode(String phone) {
        // 连接redis
        Jedis jedis = new Jedis("47.96.19.90", 23333);

        //拼接发送次数key
        String countKey = "VerifyCode" + phone + ":count";
        //验证码key
        String codeKey =  "VerifyCode" + phone + ":code";

        String count = jedis.get(countKey);

        if(count == null){
            jedis.setex(countKey,24*60*60,"1");
            setCodeKey(codeKey,jedis);
        }else if(Integer.parseInt(count) <=2){
            jedis.incr(countKey);
            setCodeKey(codeKey,jedis);
        }else{
            //今天以及发送三次了
            System.out.println("今天发送已经超过了三次");
            jedis.close();
        }

    }

    public static void setCodeKey(String codeKey,Jedis jedis){
        String code = getCode();
        System.out.println("redis给:"+codeKey+"设置验证码:"+code);
        jedis.set(codeKey,code);
        jedis.expire(codeKey,120);
    }

    //1.生成6位数字验证码
    public static String getCode() {
        String string = UUID.randomUUID().toString().substring(0, 6);
        return string;
    }
}
